package com.mobibusbr.webservices;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mobibusbr.dao.CidadeDAO;
import com.mobibusbr.model.Cidade;



public class NetClientPost {
	 
     public static void main(String[] args) {

      try {

            URL url = new URL("http://localhost:8080/WebService_MobiBusBR/rest/getCidade/post");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");

            //
            Cidade c = new Cidade();
            CidadeDAO dao = new CidadeDAO();
            c = dao.busca(12L);
            
            GsonBuilder builder = new GsonBuilder();
            Gson json = builder.create();
            String formato = json.toJson(c);
            

            OutputStream os = conn.getOutputStream();
            os.write(formato.getBytes());
            os.flush();

            if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
                    throw new RuntimeException("Failed : HTTP error code : "+ conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                    System.out.println(output);
            }

            conn.disconnect();

      } catch (MalformedURLException e) {

            e.printStackTrace();

      } catch (IOException e) {

            e.printStackTrace();

     }

    }

}

